#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2021/6/21
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :TAX43_EntRatingLevelList_SC
# @Software  :PyCharm


'''eof
name:申请企业全量纳税评级清单
code:TAX43_EntRatingLevelList_SC
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_SC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''



import json
import re
import sys
import time,datetime
import pandas as pd
import math
from dateutil import rrule
from dateutil.relativedelta import relativedelta
import io

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_SC_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]

def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def countdownTwoYearsTaxAmtCheck(spDate=None):
    try:
        """
        企业近两年纳税额校验（同时有A1表和年度汇算清缴表）
        :return:
        """
        rating_list = []
        syptSwdjxx = formatData('syptSwpjxx')
        res = {}
        for i in syptSwdjxx:
            year = i.get('SWXYPJSJ')
            level = i.get('SWXYPJ')
            if convertDataType(year, 'int') and convertDataType(level, 'str'):
            # if year not in null_type_list and level not in null_type_list:
                res.update({year: level})
        max_year = max(res.keys())
        return json.dumps({'year': max_year,'grade': res.get(max_year)}, ensure_ascii=False)
    except:
        return u'缺失值'



result = countdownTwoYearsTaxAmtCheck()
# if __name__ == '__main__':
#     import json
#     with open(r'C:\Users\john\Desktop\samples\TX_SC_DSJ.json',encoding='utf8') as ff:
#         TX_SC_DSJ = json.loads(ff.read())['parsedContent']
#     cQexecuteTime = ""
#     result = countdownTwoYearsTaxAmtCheck()
#     print(result)